package com.lagou.edu.service.impl;

import com.lagou.edu.dao.AuthCodeDao;
import com.lagou.edu.pojo.AuthCode;
import com.lagou.edu.service.AuthCodeService;
import com.lagou.edu.service.EmailService;
import com.lagou.edu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

@Slf4j
@Service
public class AuthCodeServiceImpl implements AuthCodeService {

    private final AuthCodeDao authCodeDao;
    private final UserService userService;
    private final EmailService emailService;

    public AuthCodeServiceImpl(AuthCodeDao authCodeDao, UserService userService, EmailService emailService) {
        this.authCodeDao = authCodeDao;
        this.userService = userService;
        this.emailService = emailService;
    }


    @Override
    public boolean createAuth(String email) {

        try {
            // todo 检查是否注册了
            boolean registered = userService.isRegistered(email);
            if (registered){
                return false;
            }


            // 插入验证码记录
            AuthCode authCode = new AuthCode();
            authCode.setEmail(email);

            String code = RandomStringUtils.randomNumeric(6);
            authCode.setCode(code);
            long now = System.currentTimeMillis();
            authCode.setCreatetime(new Timestamp(now));
            authCode.setExpiretime(new Timestamp(now + 10 * 60 * 1000L));

            AuthCode save = authCodeDao.save(authCode);
            if (save.getId() == null){
                log.error("验证码保存失败");
                return false;
            }

            // 调用邮件服务发送邮件
            emailService.mail(email, code);
        } catch (Exception e) {
            e.printStackTrace();

            return false;
        }
        return true;
    }

    @Override
    public int validate(String email, String code) {
        // 验证码验证
        AuthCode authCode = authCodeDao.findAuthCode(email);

        // 超时验证码失效
        if (System.currentTimeMillis() > authCode.getExpiretime().getTime()){
            return 2;
        }

        // 判断正确
        if (code.equals(authCode.getCode())){
            return 0;
        }

        // 返回错误
        return 1;
    }
}
